﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ParamSetCollection.General.Parameters.Normal
{
    public delegate void OnMainRenewValueEventHandler(string baseValue);//主更新事件
    public delegate void OnRenewValueEventHandler(byte renewMark);//子单元更新提醒
    public class DataUnit
    {
        public event OnMainRenewValueEventHandler OnMainRenewValue;
        public event OnRenewValueEventHandler OnRenewValue;

        public Type type = typeof(short);

        public byte RenewMark1 = 0;//0--无动作，1--刷新无更新,2--刷新有更新
        public byte RenewMark2 = 0;//0--无动作，1--刷新无更新,2--刷新有更新

        public ushort Data = 0;

        public DataUnit SubData = null;

        public void RenewValue(ushort val)
        {
            if(Data!=val)
            {
                Data = val;
                RenewMark1 = 2;
            }
            else
            {
                RenewMark1 = 1;
            }

            OnRenewValue?.Invoke(RenewMark1);

            SumUpRenewMark();
        }

        public void SetSubData(DataUnit du)
        {
            SubData = du;
            SubData.OnRenewValue += SubData_OnRenewValue;
        }

        private void SubData_OnRenewValue(byte renewMark)
        {
            RenewMark2 = renewMark;
            SumUpRenewMark();
        }

        private void SumUpRenewMark()
        {
            if(RenewMark1>0)
            {
                if(SubData!=null)
                {
                    if(RenewMark2>0)
                    {
                        RenewMark1 = 0;
                        RenewMark2 = 0;
                        //发送更新标志
                        ushort lowWord = Data;
                        ushort highWord = SubData.Data;

                        string v = ((Int32)((UInt32)(highWord << 16) + lowWord)).ToString();
                        OnMainRenewValue?.Invoke(v);
                    }
    
                }
                else
                {
                    RenewMark1 = 0;
                    string v = ((short)Data).ToString();
                    OnMainRenewValue?.Invoke(v);
                }

            }
        }
    }
}
